package com.example.server;

import com.example.constant.MessageType;
import com.example.pojo.Header;
import com.example.pojo.NettyMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>  </p>
 *
 * @author Chris
 * @since 2024/3/30 21:58
 */
public class HeartBeatRespHandler extends ChannelInboundHandlerAdapter {
    /**
     * 使用 slf4j 日志框架
     */
    private final static Logger log = LoggerFactory.getLogger(HeartBeatRespHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 返回心跳应答消息
        final NettyMessage message = (NettyMessage) msg;
        if (message.getHeader() != null
                && message.getHeader().getType() == MessageType.LOGIN_REQ.value()) {
            log.info("Receive client heart beat message : ===> {}", message);

            final NettyMessage heartBeat = this.buildHeartBeat();
            log.info("Send heart beat response message to client : ===> {}", heartBeat);
            ctx.writeAndFlush(heartBeat);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    private NettyMessage buildHeartBeat() {
        final Header header = new Header();
        header.setType(MessageType.HEARTBEAT_RESP.value());

        final NettyMessage message = new NettyMessage();
        message.setHeader(header);
        return message;
    }

}